package fr.emse.tatiana.replayable.analysis.graph;

import java.util.HashMap;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.ui.actions.SelectionAction;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.actions.ActionFactory;

public class RenameAction extends SelectionAction {

	public RenameAction(IWorkbenchPart part) {
		super(part);
		setLazyEnablementCalculation(true);
	}

	@Override
	protected void init() {
		setText("Edit...");
		setToolTipText("Edit text");
		setId(ActionFactory.RENAME.getId());
		setEnabled(false);
	}
	
	@Override
	protected boolean calculateEnabled() {
		Command cmd = createRenameCommand("");
		if (cmd == null)
			return false;
		return true;
	}

	public Command createRenameCommand(String name) {
		Request request = new Request("edit");
		HashMap<String, String> reqdata = new HashMap<String, String>();
		reqdata.put("editText",name);
		request.setExtendedData(reqdata);
		EditPart part = null;
		try {
			part = (EditPart) getSelectedObjects().get(0);
		} catch (Exception e) {
			return null; //TODO figure out why this action is applied in the error log and with no object selected
		}
		return part.getCommand(request);
	}

	@Override
	public void run() {
		EditPart part = (EditPart) getSelectedObjects().get(0);
		String defalt = "";
		if (part instanceof EventGraphPart) {
			EventGraphPart egp = (EventGraphPart) part;
			defalt = egp.getAnalysis().getText(egp.getAnchor());
		} else if (part instanceof ConnectionEditPart) {
			defalt = ((ConnectionEditPart)part).getCastedModel().getDesc();
		}
		InputDialog dialog = new InputDialog(getWorkbenchPart().getSite().getShell(), 
				"Edit box contents", 
				"Contents of this box:", defalt, null); 
		if (dialog.open() != Window.OK)
			return;
		execute(createRenameCommand(dialog.getValue()));
	}
	
}
